#include "UP_DAC.h"
#include "UP_GPIO.h"
#include "gd32f4xx.h"
#include "systick.h"
#include "string.h"

void DAC_init(uint32_t dac)
{
    UP_DAC_PARAMS params;
    params.triggersource = DAC_TRIGGER_SOFTWARE;
    params.wave_mode = DAC_WAVE_DISABLE;
    params.dac_align = DAC_ALIGN_8B_R;
    params.data = 0;
    DAC_init_with_params(dac, params);
}

void DAC_init_with_params(uint32_t dac, UP_DAC_PARAMS params)
{
    /* once enabled the DAC, the corresponding GPIO pin is connected to the DAC converter automatically */
    switch (dac) {
        case DAC0:
            /* code */
            GPIO_Init(PA4, 5);
            break;
        case DAC1:
            /* code */
            GPIO_Init(PA5, 5);
            break;
        default:
            break;
    }

    /* enable the clock of peripherals */
    rcu_periph_clock_enable(RCU_DAC);

    // 复位DAC
    dac_deinit();
    /* configure the DAC1 */
    dac_trigger_source_config(dac, params.triggersource); // 使用定时器3作为触发源
    dac_trigger_enable(dac);

    dac_wave_mode_config(dac, params.wave_mode); // 不使能波形
    dac_output_buffer_enable(dac);

    /* enable DAC1 and set data */
    dac_enable(dac); // 使能DAC

    dac_data_set(dac, params.dac_align, params.data); // 8位数据右对齐
    dac_software_trigger_enable(dac);     // 软件触发使能 输出数据
}